package com.youxin.admin.auth.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.admin.auth.domain.RoleDto;
import com.youxin.admin.auth.mapper.ResourceAuthorityMapper;
import com.youxin.admin.auth.model.ResourceAuthority;
import com.youxin.admin.auth.service.ResourceAuthorityService;
import com.youxin.exception.SystemException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Ace on 2019/5/23.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ResourceAuthorityServiceImpl extends ServiceImpl<ResourceAuthorityMapper, ResourceAuthority> implements ResourceAuthorityService {

    @Override
    public void batchModifyAuthorityElements(int groupId, int menuId, List<Integer> elementIds) throws SystemException {
        QueryWrapper<ResourceAuthority> condition = new QueryWrapper<>();
        condition.eq("authority_id", groupId + "");
        condition.eq("resource_id", menuId);
//        condition.eq("resource_type", AdminCommonConstant.RESOURCE_TYPE_BTN);
        this.baseMapper.delete(condition);
        List<ResourceAuthority> list = elementIds.stream().filter(elementId -> (elementId != null)).map(elementId -> {
            ResourceAuthority authority = new ResourceAuthority();
            authority.setAuthorityId(groupId);
            authority.setResourceId(elementId);
//            authority.setParentId(menuId+"");
            return authority;
        }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(list)) {
            saveBatch(list);

        }
    }

    @Override
    public void batchRemoveElementAuthority(int roleId, int menuId, List<Integer> elementIds) throws SystemException {
        QueryWrapper<ResourceAuthority> condition = new QueryWrapper<>();
        condition.eq("authority_id", roleId + "");
        condition.in("resource_id", elementIds);
        condition.eq("parent_id", -1);
        this.baseMapper.delete(condition);
    }

    @Override
    public void updateRoleMember(RoleDto roleDto) throws SystemException {
        this.baseMapper.deleteRoleMemberByRoleId(roleDto.getId());
        if (!CollectionUtils.isEmpty(roleDto.getMenuIds())) {
            this.baseMapper.insertRoleMember(roleDto.getMenuIds(), roleDto.getId(), roleDto.getUpdateBy());
        }
    }
}



